package org.jeecg.modules.middleware.quartz.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrier;
import org.jeecg.modules.wlhy.hycarrier.service.IHyCarrierService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.shipping.dto.YunFuTongShippingNoteDTO;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.yunfutong.service.IhyYunfutongServiceAPI;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 运税宝--上报运单轨迹
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
public class YunShuiBaoUploadJobService implements Job {

    @Autowired
    private IhyYunfutongServiceAPI yunfutongServiceAPI;
    @Autowired
    private IHyShippingNoteService hyShippingNoteService;
    @Autowired
    private IHyOrderService hyOrderService;
    @Autowired
    private IHyDriverService hyDriverService;
    @Autowired
    private IHyVehicleService hyVehicleService;
    @Autowired
    private IHyCarrierService carrierService;
    @Autowired
    private IHyShippingNoteBillService hyShippingNoteBillService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        log.info("运税宝--上报运单开始");
        //获取已经结算完未上报的运单
        QueryWrapper<YunFuTongShippingNoteDTO> queryWrapper = new QueryWrapper();
        //运单
        queryWrapper.eq("shipping.shipping_status", "5");
        queryWrapper.eq("shipping.shipping_pay_status", "6");
        queryWrapper.ne("shipping.daoda_upload_status","1");

        Page<YunFuTongShippingNoteDTO> page = new Page<>(1, 1000);
        IPage<YunFuTongShippingNoteDTO> pageList = yunfutongServiceAPI.getYunShuiBaoPageList(page, queryWrapper);
        Result<?> result = yunfutongServiceAPI.login();
        if (!result.isSuccess()) {
            throw new JobExecutionException(result.getMessage());
        }
        String token = result.getResult().toString();
        int num = 0;
        for (YunFuTongShippingNoteDTO yunFuTongShippingNoteDTO : pageList.getRecords()) {
            try {

                if (yunFuTongShippingNoteDTO.getStatusDtLoading() == null || yunFuTongShippingNoteDTO.getStatusDtUnloading() == null) {
                    hyShippingNoteService.lambdaUpdate()
                            .eq(HyShippingNote::getId,yunFuTongShippingNoteDTO.getId())
                            .set(HyShippingNote::getDaodaUploadStatus, "2")
                            .set(HyShippingNote::getDaodaFailureReason, "装卸货时间不能为空")
                            .update();
                    continue;
                }
                long time1 = yunFuTongShippingNoteDTO.getStatusDtLoading().getTime();
                long time2 = yunFuTongShippingNoteDTO.getStatusDtUnloading().getTime();
                // 计算毫秒数差
                long diff = Math.abs(time1 - time2);
                // 将毫秒数差转换为分钟数
                long minutes = diff / (60 * 1000);
                if (minutes < 5) {
                    log.error("运单号为"+yunFuTongShippingNoteDTO.getShippingNoteNumber()+"实际装货时间与实际发货时间不能低于5分钟");
                    hyShippingNoteService.lambdaUpdate()
                            .eq(HyShippingNote::getId,yunFuTongShippingNoteDTO.getId())
                            .set(HyShippingNote::getDaodaUploadStatus, "2")
                            .set(HyShippingNote::getDaodaFailureReason, "实际装货时间与实际发货时间不能低于5分钟")
                            .update();
                    continue;
                }
                HyOrder order = hyOrderService.getById(yunFuTongShippingNoteDTO.getOrderId());
                if (order == null) {
                    log.error("运单号为"+yunFuTongShippingNoteDTO.getShippingNoteNumber()+"货源为空!");
                    hyShippingNoteService.lambdaUpdate()
                            .eq(HyShippingNote::getId,yunFuTongShippingNoteDTO.getId())
                            .set(HyShippingNote::getDaodaUploadStatus, "2")
                            .set(HyShippingNote::getDaodaFailureReason, "货源不存在")
                            .update();
                    continue;
                }
                HyDriver driver = hyDriverService.getById(yunFuTongShippingNoteDTO.getDriverId());
                if (driver == null) {
                    log.error("运单号为"+yunFuTongShippingNoteDTO.getShippingNoteNumber()+"司机为空!");
                    hyShippingNoteService.lambdaUpdate()
                            .eq(HyShippingNote::getId,yunFuTongShippingNoteDTO.getId())
                            .set(HyShippingNote::getDaodaUploadStatus, "2")
                            .set(HyShippingNote::getDaodaFailureReason, "司机信息不存在")
                            .update();
                    continue;
                }
                HyVehicle vehicle = hyVehicleService.getById(yunFuTongShippingNoteDTO.getVehicleId());
                if (vehicle == null) {
                    log.error("运单号为"+yunFuTongShippingNoteDTO.getShippingNoteNumber()+"车辆信息不存在!");
                    hyShippingNoteService.lambdaUpdate()
                            .eq(HyShippingNote::getId,yunFuTongShippingNoteDTO.getId())
                            .set(HyShippingNote::getDaodaUploadStatus, "2")
                            .set(HyShippingNote::getDaodaFailureReason, "车辆信息不存在")
                            .update();
                    continue;
                }
                HyCarrier carrier = null;
                if (yunFuTongShippingNoteDTO.getPayType().equals("2")){
                    carrier = carrierService.getById(yunFuTongShippingNoteDTO.getCarrierId());
                    if (carrier == null) {
                        log.error("运单号为"+yunFuTongShippingNoteDTO.getShippingNoteNumber()+"代收人为空!");
                        hyShippingNoteService.lambdaUpdate()
                                .eq(HyShippingNote::getId,yunFuTongShippingNoteDTO.getId())
                                .set(HyShippingNote::getDaodaUploadStatus, "2")
                                .set(HyShippingNote::getDaodaFailureReason, "代收人信息不存在")
                                .update();
                        continue;
                    }
                }
                HyShippingNoteBill shippingNoteBill = hyShippingNoteBillService.getBillByShippingId(yunFuTongShippingNoteDTO.getId());
                if (shippingNoteBill == null) {
                    log.error("运单号为"+yunFuTongShippingNoteDTO.getShippingNoteNumber()+"流水为空!");
                    hyShippingNoteService.lambdaUpdate()
                            .eq(HyShippingNote::getId,yunFuTongShippingNoteDTO.getId())
                            .set(HyShippingNote::getDaodaUploadStatus, "2")
                            .set(HyShippingNote::getDaodaFailureReason, "流水不存在")
                            .update();
                    continue;
                }

                //2、接口调用顺序：1)请求登录，获取token  2)文件上传 3)新增车辆 4)新增司机 5)新增运单(上传运单时 需要上传 银行回单、合同、运输凭证)
                //查询司机是否存在
                if (!yunfutongServiceAPI.IsExist(driver.getIdcard(), token, null)) {
                    //上传司机证件
                    HyDriver uploadDriver = yunfutongServiceAPI.uploadDriver(driver, token);
                    //添加司机
                    Result<?> result1 = yunfutongServiceAPI.addDriver(uploadDriver, token, null, vehicle);
                    if (!result1.isSuccess() && !result1.getMessage().equals("已存在该手机号")) {
                        Result<?> addDriverResult = yunfutongServiceAPI.addDriver(driver, token, null, vehicle);
                        if (!addDriverResult.isSuccess()) {
                            hyShippingNoteService.lambdaUpdate()
                                    .eq(HyShippingNote::getId,yunFuTongShippingNoteDTO.getId())
                                    .set(HyShippingNote::getDaodaUploadStatus, "2")
                                    .set(HyShippingNote::getDaodaFailureReason, result1.getMessage())
                                    .update();
                            log.error("运单号为"+yunFuTongShippingNoteDTO.getShippingNoteNumber()+"添加司机到草稿箱失败,原因为"+addDriverResult.getMessage());
                            continue;
                        }
                    }
                }
                if (!yunfutongServiceAPI.IsExist(null, token, vehicle.getVehicleNumber())) {
                    //上传车辆证件
                    HyVehicle hyVehicle = yunfutongServiceAPI.uploadVehicle(vehicle, token);
                    Result<?> result2 = yunfutongServiceAPI.addVehicle(hyVehicle, driver, token);
                    if (!result.isSuccess()) {
                        hyShippingNoteService.lambdaUpdate()
                                .eq(HyShippingNote::getId,yunFuTongShippingNoteDTO.getId())
                                .set(HyShippingNote::getDaodaUploadStatus, "2")
                                .set(HyShippingNote::getDaodaFailureReason, result2.getMessage())
                                .update();
                        log.error("运单号为"+yunFuTongShippingNoteDTO.getShippingNoteNumber()+"请求代开添加车辆失败，原因为"+result2.getMessage());
                        continue;
                    }
                }

                //上传运单凭证
                HyShippingNote shippingNoteUpload = yunfutongServiceAPI.shippingNoteUpload(token, yunFuTongShippingNoteDTO);
                HyShippingNoteBill hyShippingNoteBill = yunfutongServiceAPI.ShippingNoteBillUpload(token,shippingNoteBill);

                //添加运单
                Result<?> result3 = yunfutongServiceAPI.addShippingNote(shippingNoteUpload, driver, vehicle, token, hyShippingNoteBill,carrier);
                if (!result3.isSuccess()) {
                    hyShippingNoteService.lambdaUpdate()
                            .eq(HyShippingNote::getId,yunFuTongShippingNoteDTO.getId())
                            .set(HyShippingNote::getDaodaUploadStatus, "2")
                            .set(HyShippingNote::getDaodaFailureReason, result3.getMessage())
                            .update();
                    log.error("运单号为"+yunFuTongShippingNoteDTO.getShippingNoteNumber()+"请求代开添加运单失败，原因为"+result3.getMessage());
                    continue;
                }
                Result<?> result4 = yunfutongServiceAPI.uploadTraces(shippingNoteUpload, vehicle,token);
                if (!result4.isSuccess()) {
                    hyShippingNoteService.lambdaUpdate()
                            .eq(HyShippingNote::getId,yunFuTongShippingNoteDTO.getId())
                            .set(HyShippingNote::getDaodaUploadStatus, "2")
                            .set(HyShippingNote::getDaodaFailureReason, result4.getMessage());
                    log.error("运单号为"+yunFuTongShippingNoteDTO.getShippingNoteNumber()+"请求代开添加运单失败，原因为"+result4.getMessage());
                } else {
                    hyShippingNoteService.lambdaUpdate()
                            .eq(HyShippingNote::getId,yunFuTongShippingNoteDTO.getId())
                            .set(HyShippingNote::getDaodaUploadStatus, "1")
                            .set(HyShippingNote::getDaodaFailureReason, result4.getMessage());
                }
                num++;
            }catch (Exception e){
                log.error("运单号为："+ yunFuTongShippingNoteDTO.getShippingNoteNumber()+"的运单推送失败,原因为"+e.getMessage());
                continue;
            }
        }
        log.info("运税宝--上报运单结束，本次共上报"+num+"条数据");
    }
}
